class OauthController < ApplicationController
  skip_filter :ensure_is_authenticated_in_fb
  def new
    session[:at]=nil
    redirect_to authenticator.authorize_url(:scope => 'publish_stream', :display => 'page')
  end
  
  def create
    mogli_client = Mogli::Client.create_from_code_and_authenticator(params[:code],authenticator)
    
    #session[:at]=mogli_client.access_token
    #create a user if not exists
    fb_user = Mogli::User.find("me",Mogli::Client.new(mogli_client.access_token))
    user = User.find_by_fb_uid(fb_user.id)
    #if new user, create new one
    if !user
      user = User.new
      user.fb_uid = fb_user.id
      user.fb_at = mogli_client.access_token
      user.name = fb_user.name
      user.email = fb_user.id+"@fbuser.com"
      user.login = fb_user.id
      pwd = Array.new(10) {(rand(122-97) + 97).chr }.join
      user.password = pwd
      user.verified = true
      user.password_confirmation = pwd
      user.save!
    else #if returning user, then update access token
      user.fb_at = mogli_client.access_token
      user.save!
    end
    
    #try to authenticate user
    #remove old session if exists
    if current_user_session
      current_user_session.destroy
    end
    #create session
    @user_session = UserSession.create(user, true)
    @user_session.save
    logger.info(@user_session.inspect)
    #redirect to canvas page
    html = ""
    html +="<script>"
    html +="window.top.location.href=\"http://apps.facebook.com/#{WEBAPP_CONFIG["facebook_canvas"]}\""
    html +="</script>"
    render :text=>html
    
  end
  
  #def index
  #  redirect_to new_oauth_path and return unless session[:at]
  #  user = Mogli::User.find("me",Mogli::Client.new(session[:at]))
  #  @user = user
  #  @posts = user.posts
  #  puts "in indexxxxxxxxxxxx"
  #end
  
  def authenticator
    @authenticator ||= Mogli::Authenticator.new(WEBAPP_CONFIG['facebook_client_id'],WEBAPP_CONFIG['facebook_secret'],oauth_callback_url)
  end
  
  
end
